<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="10">
        <div class="panel-info">
          <div class="panel-title">SMT机台列表</div>
          <div class="panel-body">
            <el-button type="success" class="fr" @click="openimportVisible" style="margin-left: 5px"
              v-permission="'smt.add'">导入 </el-button>
            <div class="filter-container">
              <el-select class="filter-item" @change="researchMain" clearable v-model="queryMain.machineId"
                placeholder="请选择SMT机台" style="width:200px">
                <el-option v-for="i in machineCodeOptions" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
              <el-select class="filter-item" @change="researchMain" clearable v-model="queryMain.is_active"
                placeholder="选择状态" style="width:150px">
                <el-option label="全部" value=""></el-option>
                <el-option label="已失效" value="N"></el-option>
                <el-option label="生效中" value="Y"></el-option>
              </el-select>
              <el-input class="filter-item" clearable @change="researchMain" v-model="queryMain.moInfo"
                placeholder="请输入SMT工单" style="width:200px">
              </el-input>

              <el-button class="filter-item" type="success" plain @click="researchMain">查询</el-button>
            </div>
            <z-table :list="listMain" :tableProps="tablePropsMain" @current-change="getItemList" :columns="columnsMain"
              @deleteItem="deleteMain">
              <template v-slot:content="v">
                <span v-if="v.key === 'is_active'" class="text-label" :class="statusClass[v.row['is_active']]">
                  {{ status[v.row['is_active']] }}
                </span>
                <span v-else>{{ v.row[v.key] }}</span>
              </template>
              <template v-slot:operation="v">
                <a href="#" class="text-blue" v-permission="'smt.add'"
                  @click.prevent.stop="editMain(v.row)">复制&nbsp;</a>
                <a href="#" class="text-yellow" v-permission="'smt.edit'" v-if="v.row.is_active == 'Y'"
                  @click.prevent.stop="enableOrdisableSmt(v.row)">失效&nbsp;</a>
                <a href="#" class="text-yellow" v-permission="'smt.edit'" v-if="v.row.is_active == 'N'"
                  @click.prevent.stop="enableOrdisableSmt(v.row)">激活&nbsp;</a>
                <!-- <a href="#" class="text-red" @click.prevent.stop="deleteMain(v.row)">删除</a> -->
              </template>
            </z-table>

            <z-pagination :pagination="paginationMain" :total="totalMain" :page.sync="queryMain.page"
              :limit.sync="queryMain.size" @change="getMainList"></z-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="14" v-show="itemFlag">
        <div class="panel-info">
          <div class="panel-title">机台详情</div>
          <div class="panel-body">
            <div style=" min-height: 40px">
              <!-- <el-button class="fr" @click="createItem" type="primary" plain>添加物料</el-button> -->
              <el-input style="width: 300px" placeholder="输入物料号/物料名/元件名查询按回车" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="research" @clear="research" v-model="query.queryString">
              </el-input>
              <el-button class="ml-5" type="success" plain @click="research">查询</el-button>
            </div>
            <z-table :list="list" :tableProps="tableProps" :columns="columns">
            </z-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.page"
              @change="getList"></z-pagination>
          </div>
        </div>
      </el-col>
    </el-row>

    <z-form-dialog :name="name" :data="dataMain" :formProps="formProps" :fields="fields" @submit="saveMain"
      :submitLoading="submitLoading" :visible.sync="editMainFormVisible">
    </z-form-dialog>
    <el-dialog title="导入SMT料号" width="50%" :visible.sync="importVisible">
      <el-form :model='queryAdd.info' :rules="rules">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="请选择SMT机台" prop="machine_id">
              <el-select v-model="queryAdd.info.machine_id" placeholder="请选择SMT机台" style="width:100%"
                @change="machineCodeChange">
                <el-option v-for="i in machineCodeOptions" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请选择SMT工单" prop="mo_id">
              <el-select v-model="queryAdd.info.mo_id" placeholder="请选择SMT工单" style="width:100%">
                <el-option v-for="i in machineOptions" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="请输入备注">
              <el-input type="textarea" rows="3" v-model="queryAdd.info.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <!-- <div style="margin-bottom: 10px"><a href="#">下载导入模板</a></div> -->
        <upload-excel-component ref="uploadExcel" :on-success="handleSuccess" :before-upload="beforeUpload"
          style="margin-bottom: 20px" />
        <el-button type="primary" @click.native="importSave" :loading="importSaveLoading"> 确认 </el-button>
        <el-button @click="importVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
export default {
  mixins: [commonMixin],
  name: 'smt',
  components: { UploadExcelComponent },
  data: function () {
    return {
      api: this.$api.smt,
      apiList: this.$api.smt + 'getSMTDetailList',
      name: 'SMT料表管理',
      machineCodeOptions: [], // 机台下拉
      machineOptions: [], // 工单下拉
      queryAdd: {
        info: {},
        details: [],
      },
      rules: {
        machine_id: [{ required: true, message: '', trigger: 'blur' }],
        mo_id: [{ required: true, message: '', trigger: 'blur' }],
      },
      columnsMain: [
        { title: '工单机台', key: 'machine_name' },
        { title: '工单编号', key: 'mo_no' },
        { title: '版本', key: 'version', width: 60 },
        { title: '备注', key: 'remark', width: 100 },
        { title: '状态', key: 'is_active', width: 70 },
        { title: '操作人', key: 'modify_user', width: 100 },
        { title: '操作时间', key: 'modify_time', width: 140 },
      ],
      tableProps: {
        border: true,
        //opsColWith: 140, //不定义默认80
        hideOperations: true,
      },
      columns: [
        { title: '安装号码', key: 'install_no', width: 120 },
        { title: '元件名', key: 'key_part_no', width: 140 },
        { title: '送料器类型', key: 'feeder_type', width: 140 },
        { title: '走带间距', key: 'space_between', width: 70 },
        { title: '图样名', key: 'material_name', width: 100 },
        { title: '总数', key: 'qty', width: 50 },
        { title: '备注', key: 'remark', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [
        { title: '工单机台', key: 'machine_id', name: 'select', props: { disabled: true }, options: [], span: 24 },
        { title: '工单编号', key: 'mo_id', name: 'select', options: [], span: 12 },
        { title: '版本', key: 'version', span: 12 },
        { title: '备注', key: 'remark', span: 24, name: 'texarea' },
      ],
      initData: {},
      tablePropsMain: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '120',
      },
      dataMain: {},
      editMainFormVisible: false, //编辑模态框的显示状态
      listMain: [],
      totalMain: 0,
      queryMain: {
        page: 1,
        size: 10,
        is_active: '',
      },
      itemFlag: false, // 详细表显示
      type: '',
      mainTitle: '',
      status: { Y: '生效中', N: '已失效' },
      statusClass: { N: 'bg-gray', Y: 'bg-green' },
      paginationMain: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, ->, total',
      },
      importSaveLoading: false,
      importVisible: false,
      curSmt: {},
    }
  },
  methods: {
    // 导入机台下拉
    machineCodeChange(value) {
      // this.queryAdd.info.mo_id = null
      if (this.queryAdd.info.mo_id) this.queryAdd.info.mo_id = null
      this.$request(this.api + 'getMoByMachine', { queryString: value }).then((r) => {
        if (r.length) {
          this.machineOptions = r.map((i) => {
            return {
              label: i.mo_no,
              value: i.mo_id,
            }
          })
        } else {
          this.machineOptions = []
        }
      })
    },
    machineCodeCopy(value) {
      this.setFieldOptions('mo_id', [])
      this.$request(this.api + 'getMoByMachine', { queryString: value }).then((r) => {
        if (r.length) {
          this.setFieldOptions('mo_id', r, 'mo_id', 'mo_no')
        }
      })
    },
    researchMain() {
      this.clearMainData()
      this.query = {
        queryString: null,
        size: 10,
        page: 1,
      }
      this.queryMain.page = 1
      this.listMain = []
      this.totalMain = 0
      this.getMainList()
    },
    clearMainData() {
      this.itemFlag = false
      this.list = []
      this.curSmt = {}
    },
    reset() {
      this.queryAdd = {
        info: {},
        details: [],
      }
      if (this.$refs.uploadExcel) this.$refs.uploadExcel.clearFile()
    },
    init() {
      this.$request(this.$api.smt + 'getMachineCode', {}).then((r) => {
        this.setFieldOptions('machine_id', r, 'id', ['machine_code', 'machine_name'])
        this.machineCodeOptions = r.map((i) => {
          return {
            value: i.id,
            label: i.machine_code + ' ' + i.machine_name,
          }
        })
      })
    },
    formatAfterGet(data) {
      //依据实际需求处理
      this.singleMaOptions(data.material_id)
      return data
    },
    // 导入
    openimportVisible() {
      this.importVisible = true
      this.reset()
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 50
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning',
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.queryAdd.info['version'] = header[1]
      this.queryAdd.info['is_active'] = 'Y'
      this.queryAdd.details = []
      let arr = results.slice(3)
      arr.forEach((i, j) => {
        this.queryAdd.details.push({
          seq: j + 1,
          install_no: i['Version'],
          material_code: i[header[1]],
          remark: i['__EMPTY'],
          feeder_type: i['__EMPTY_1'],
          space_between: i['__EMPTY_2'],
          material_name: i['__EMPTY_8'],
          qty: i['__EMPTY_15'],
        })
      })
      console.log(this.queryAdd, 'this.queryAdd')
      /*this.tableHeader = header*/
    },
    importSave: function () {
      this.importSaveLoading = true
      let url = this.api + 'importSMTData'
      if (this.queryAdd.details.length <= 0) {
        this.$message({
          message: '请先选择Excel',
          type: 'error',
        })
        this.importSaveLoading = false
      } else if (!this.queryAdd.info.machine_id) {
        this.$message({
          message: '机台 需要必填',
          type: 'error',
        })
      } else if (!this.queryAdd.info.mo_id) {
        this.$message({
          message: '工单 需要必填',
          type: 'error',
        })
      } else {
        this.$request(url, this.queryAdd, 'post')
          .then((r) => {
            this.importSaveLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.importVisible = false
            this.reset()
            this.$refs.uploadExcel.clearFile()
            this.getMainList()
          })
          .catch(() => {
            this.importSaveLoading = false
          })
      }
    },
    singleMaOptions(v) {
      this.setFieldOptions('material_id', [])
      if (v) {
        this.$request(this.$api.mat + 'getmatandsku', {
          id: v,
        })
          .then((r) => {
            this.setFieldOptions('material_id', r, 'id', ['key_part_no', 'key_part_name'])
          })
          .catch(() => {})
      }
    },
    getItemList(v) {
      console.log(v)
      this.curSmt = v
      if (!v) return
      this.itemFlag = true
      this.query.mainId = v.id
      this.queryMain.smt_id = v.id
      this.getList()
    },
    getMainList() {
      this.pageLoading = true
      let url = this.api + 'getSMTMainList'
      this.$request(url, this.queryMain)
        .then((r) => {
          this.pageLoading = false
          this.listMain = r.list
          this.totalMain = r.total
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    formatBeforeSave(data) {
      let tmp = _.cloneDeep(data)
      tmp.bom_id = this.curSmt.id
      return tmp
    },
    editMain(v) {
      this.dataMain = {}
      this.mainTitle = '复制SMT--会同时复制此SMT下的物料明细'
      this.machineCodeCopy(v.machine_id)
      this.dataMain = {
        id: v.id,
        machine_id: v.machine_id,
        mo_id: v.mo_id,
        version: v.version,
        is_active: v.is_active,
        remark: v.remark,
      }
      this.editMainFormVisible = true
    },
    deleteMain(v) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        let url = this.api + 'deleteSMTMainById'

        this.$request(url + '/' + v.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.clearMainData()
            this.getMainList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    saveMain() {
      this.submitLoading = true
      let url = this.api + 'copySMTData'
      let data = this.dataMain
      this.clearMainData()
      this.$request(url, data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editMainFormVisible = false
          this.getMainList()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    enableOrdisableSmt(v) {
      let status = { N: '激活', Y: '失效' }
      this.$confirm('确定要' + status[v.is_active] + '这条记录？', '操作确认').then(() => {
        this.clearMainData()
        this.pageLoading = true

        this.$request(this.api + 'enableOrDisableSMT/' + v.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getMainList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
  },
  created: function () {
    this.getMainList()
    this.init()
  },
}
</script>
<style scoped>
</style>
